package com.itbaiyun.jcclientsdk.client;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.itbaiyun.common.exception.BusinessException;
import com.itbaiyun.common.model.type.LovelornSentence;
import com.itbaiyun.common.model.type.WeatherInfo;
import com.itbaiyun.common.model.type.param.WeatherParam;
import com.itbaiyun.jcclientsdk.model.User;
import com.itbaiyun.jcclientsdk.utils.SignUtil;
import com.itbaiyun.project.common.BaseResponse;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义调用API接口的客户端
 */
@Slf4j
public class JCClient {

    private final String accessKey;

    private final String secretKey;

    public static final String GATEWAY_HOST = "http://localhost:8090";

    public JCClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.get(GATEWAY_HOST + "/api/name/get", paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST + "/api/name/post")
                .addHeaders(getHeaderMap(name))
                .body(name)
                .charset("utf-8")
                .execute();
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }

    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);
//        hashMap.put("secretKey",secretKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body", body);
        //sign = body + . + secretKey
        hashMap.put("sign", SignUtil.getSign(body, secretKey));
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        return hashMap;
    }

    public String getNameByJson(User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST + "/api/name/user")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .charset("UTF-8")
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }


    /**
     * <p>随机一条失恋文案, 感情遇到挫折也不要灰心, 下一个更好~</p>
     *
     * @return BaseResponse<LovelornSentence> response
     * @build <p>Build by Adorabled4 at 2023-12-30. Driver by FreeMarker Template Engine</p>
     */
    public BaseResponse<LovelornSentence> callLovelornSentence() {
        try {

            String result = HttpRequest.get(GATEWAY_HOST + "/api/common/lovelorn").addHeaders(getHeaderMap("null")).execute().body();
            BaseResponse<LovelornSentence> baseResponse = JSONUtil.toBean(result, BaseResponse.class);
            if (baseResponse.getCode() == 0) {
                String dataStr = JSONUtil.toJsonStr(baseResponse.getData());
                if (dataStr == null || dataStr.equals("")) {
                    log.error("\u001B[31m" + this.getClass() + "\u001B[0m: " + "[JCClient] 调用接口失败 --" + baseResponse.toString());
                }
                return baseResponse;
            } else {
                throw new BusinessException(baseResponse.getCode(), baseResponse.getMessage());
            }
        } catch (IORuntimeException e) {
            log.error("\u001B[31m" + e.getClass() + "\u001B[0m: " + "[JCClient] 访问服务器失败 --" + e.getMessage());
        } catch (RuntimeException e) {
            log.error("\u001B[31m" + e.getClass() + "\u001B[0m: " + "[JCClient] 调用接口失败 --" + e.getMessage());
        }
        return null;
    }

    /**
     * <p>输入地区名称, 返回当地天气情况</p>
     *
     * @param param param.WeatherParam param
     * @return BaseResponse<WeatherInfo> response
     */
    public BaseResponse<WeatherInfo> callWeatherNow(String param) {
        try {
            String result = HttpRequest.get(GATEWAY_HOST + "/api/common/weather").addHeaders(getHeaderMap(param)).body(param, String.valueOf(StandardCharsets.UTF_8)).execute().body();


            BaseResponse<WeatherInfo> baseResponse = JSONUtil.toBean(result, BaseResponse.class);
            if (baseResponse.getCode() == 0) {
                String dataStr = JSONUtil.toJsonStr(baseResponse.getData());
                if (dataStr == null || dataStr.equals("")) {
                    log.error("\u001B[31m" + this.getClass() + "\u001B[0m: " + "[JCClient] 调用接口失败 --" + baseResponse.toString());
                }
                return baseResponse;
            } else {
                throw new BusinessException(baseResponse.getCode(), baseResponse.getMessage());
            }
        } catch (IORuntimeException e) {
            log.error("\u001B[31m" + e.getClass() + "\u001B[0m: " + "[JCClient] 访问服务器失败 --" + e.getMessage());
        } catch (RuntimeException e) {
            log.error("\u001B[31m" + e.getClass() + "\u001B[0m: " + "[JCClient] 调用接口失败 --" + e.getMessage());
        }
        return null;
    }


}
